//引入axios
import axios from "axios";
import qsString from "querystring";
//引入路由的模块
import router from '../router'
//设置基础地址
let baseUrl = "/api";

//封装拦截器
//请求拦截
//使用场景一般就是 添加请求头
axios.interceptors.request.use((req) => {
  //设置请求头
  //剔除掉对登录接口添加请求头 因为 token是登录成功之后才出现的令牌
  console.log(req, "请求拦截器");
  if (req.url != "/api/userlogin") {
    req.headers.authorization = JSON.parse(
      sessionStorage.getItem("userinfo")
    ).token;
  }
  return req;
});

//响应拦截器
//使用场景是什么  是全局性的拦截错误
axios.interceptors.response.use((res) => {
  //请设置请求头,并携带验证字符串
  //登录已过期或访问权限受限
  if(res.data.msg=='请设置请求头,并携带验证字符串'){
    alert(res.data.msg)
    //强制用户跳转到 登录页
    router.push('/login')
  }
  if(res.data.msg=='登录已过期或访问权限受限'){
    alert(res.data.msg)
    //强制用户跳转到 登录页
    router.push('/login')
  }
  return res.data
});

/* 
get
url
params
*/
export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .get(baseUrl + url, {
        params,
      })
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};

/* 
post
url
params
isFile
*/
export const post = (url, params = {}, isFile = false) => {
  let data = {};
  if (isFile) {
    data = new FormData();
    for (let i in params) {
      data.append(i, params[i]);
    }
  } else {
    data = qsString.stringify(params);
  }
  return new Promise((resolve, reject) => {
    axios
      .post(baseUrl + url, data)
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};
